package com.jymf.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;

public class HttpClientUtils {
	
	private final static Log log=LogFactory.getLog(HttpClientUtils.class);
	  
	private static PoolingHttpClientConnectionManager connMgr;
	private static RequestConfig requestConfig;
	private static final int MAX_TIMEOUT = 7000;
	
	static{
		connMgr = new PoolingHttpClientConnectionManager();
		//设置连接池大小
		connMgr.setMaxTotal(10);
		connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
		
		RequestConfig.Builder configBuilder = RequestConfig.custom();
		//设置连接超时
		configBuilder.setConnectTimeout(MAX_TIMEOUT);
		//设置读取超时
		configBuilder.setSocketTimeout(MAX_TIMEOUT);
		//设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
		
		requestConfig = configBuilder.build(); 
		
	}
	
	/**
	 * post无参提交
	 * @Title: postForm 
	 * @param apiUrl
	 * @return Map<String,Object>
	 * @author zyj
	 * @date 2016年5月10日 上午9:23:46 
	 * @throws
	 */
	public static Map<String, Object> postForm(String apiUrl){
		return postMapForm(apiUrl, new HashMap<String, Object>());
	}
	
	/**
	 * post(json) 提交
	 * @Title: postJsonForm 
	 * @param apiUrl
	 * @param json
	 * @return Map<String,Object>
	 * @author zyj
	 * @date 2016年5月10日 上午9:21:39 
	 * @throws
	 */
	public static Map<String, Object> postJsonForm(String apiUrl, Object json){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		try {
			httpPost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
		
			response = httpClient.execute(httpPost);
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				String value = entity.toString();
				resultMap.put("1", value);
			}else{
				resultMap.put("5", "无法连接第三方接口！");
		    }
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			resultMap.put("2", "客户端协议异常！");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			resultMap.put("4", "IO异常,传输错误！");
			e.printStackTrace();
		} finally{
			if (response != null) {  
                try {  
                    EntityUtils.consume(response.getEntity());  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
		}
		
		return resultMap;
	}
	
	/**
	 * post（map方式）提交 参数K-V
	 * @Title: postForm 
	 * @return String
	 * @author zyj
	 * @date 2016年5月9日 下午5:27:58 
	 * @throws
	 */
	public static Map<String, Object> postMapForm(String apiUrl, Map<String, Object> map){
		
		Map<String, Object> resultMap  = new HashMap<String, Object>();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		try {
			httpPost.setConfig(requestConfig);
			List<NameValuePair> pairList = new ArrayList<NameValuePair>();
			Set<Entry<String, Object>> set =  map.entrySet();
			for(Entry<String, Object> entry:set){
				String key = entry.getKey();
				Object value = entry.getValue();
				
				NameValuePair pair = new BasicNameValuePair(key, String.valueOf(value));
				pairList.add(pair);
			}
			
			//放置参数
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
			
			response = httpClient.execute(httpPost);
			//httpClient.execute(response);
			log.info(response.toString());
			HttpEntity entity = response.getEntity();  
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){    
				String value = EntityUtils.toString(entity, "UTF-8");
				 resultMap.put("code", "1");
				 resultMap.put("data", value);
			}else{
			   resultMap.put("code", "5");
			   resultMap.put("data", "无法连接第三方接口！");
		    }
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			resultMap.put("code", "2");
			resultMap.put("data", "客户端协议异常！");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			resultMap.put("code", "3");
			resultMap.put("data", "IO异常,传输错误！");
			e.printStackTrace();
		} finally{
			if (response != null) {  
                try {  
                    EntityUtils.consume(response.getEntity());  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
		}
		
		return resultMap;
	}
	
    
}
